package com.td.core.obj.logic;

import java.util.LinkedList;

import com.td.core.globals.TDGlobals;
import com.td.core.obj.Player;
import com.td.core.obj.TDMap;
import com.td.core.obj.TDPoint;
import com.td.core.obj.tower.Tower;
import com.td.core.obj.unit.Unit;
import com.td.core.obj.utils.PointConverter;
import com.td.core.pathfinding.IPathfinding;
import com.td.core.pathfinding.PathPoint;
import com.td.core.pathfinding.RiskAStar;
import com.td.core.pathfinding.exception.PathNotFoundException;

public class LevelLogic {

	private int lastLevel = -1;
	
	float oldLife = 0;
	
	float lifeDX = 1.6f;
	
	private	static float LIFE_START = 3;

	private static float AWARD_START = 2;
	private static float AWARD_DX = 0.34f;
	
	private static float SPEED_START = 1.5f;
	private static float SPEED_DX = 0.02f;
	
	
	
	public void createUnits(Player player, int level) {
			
		float award = AWARD_START + AWARD_DX * level;
		
		float speed = SPEED_START + SPEED_DX * level;
		
		float life = LIFE_START + oldLife * lifeDX;
		
		if(lastLevel != level) {
//			System.out.println("new Level");
			oldLife = life;
			
			if(lifeDX >= 1.2f)
				lifeDX -= 0.025f;
			lastLevel = level;
		}
		
		int space = TDMap.BLD_X / TDGlobals.totalUnits;
		
		player.getUnits().clear();
		
		for(int j = 0 ; j < TDGlobals.totalUnits ; j++) {
				
			Unit u = new Unit(new TDPoint(j*space + TDGlobals.unitStart.getX(), TDGlobals.unitStart.getY()));
			
			u.setAward(award);
			u.setLife(life);
			u.setSpeed(speed);
			
			u.setPath(calculatePath(u.getPosition(), TDGlobals.unitTarget, player));
			
			UnitLogic.addUnit(player, u);
		
		}
//		System.out.println("level: " + level);	
//		System.out.println("award: " + award);
//		System.out.println("speed: " + speed);
//		System.out.println("life: " + life);
//		System.out.println("lifeDX: " + lifeDX);
	}
	
	private LinkedList<TDPoint> calculatePath(TDPoint start, TDPoint target, Player player) {
		
		IPathfinding aStar = new RiskAStar();
		
		int[][] map = new int[TDMap.MAP_X][TDMap.MAP_Y];

		for(int i = 0 ; i < TDMap.MAP_X ; i++)
			for(int j = 0 ; j < TDMap.MAP_Y ; j++)
				map[i][j] = 0;
		
		for(Tower tower : player.getTowers()) {
			
			int x = tower.getPosition().getX();
			int y = tower.getPosition().getY();
			for(int i = 0 ; i < tower.getSize() ; i++)
				for(int j = 0 ; j < tower.getSize() ; j++)
					map[x + i][y + j] = IPathfinding.OBSTACLE;
			
		}
		
		PathPoint ppStart = PointConverter.toPathPoint(start);
		PathPoint ppTarget = PointConverter.toPathPoint(target);
		
		
		LinkedList<TDPoint> path = new LinkedList<TDPoint>();
		
		try {
			for(PathPoint pathPoint :  aStar.find(ppStart, ppTarget, map))				
				path.add(PointConverter.toTDPoint(pathPoint));
		
		} catch (PathNotFoundException e) {
			
			//TODO 
			//cos z tym trzeba zrobic
			e.printStackTrace();
		}
		
		
		return path;
	}
}
